var loc = window.location;
var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
var abspath = loc.href.substring(0, loc.href.length - ((loc.pathname + loc.search + loc.hash).length - pathName.length));

var strSecIncidentsUrl = abspath+'incidents/ajax/getsecincidents.php';
var strHealthAvailUrl = abspath+'incidents/ajax/gethealthavailincidents.php';
var strRequestsUrl = abspath+'incidents/ajax/getrequests.php';
var strIncidentViewUrl = abspath+'incidents/ajax/incidentview.php';
var strFeedsUrl = abspath+'incidents/ajax/getfeeds.php';
var strFeedsViewUrl = abspath+'incidents/ajax/feedview.php';

var chart;
$(document).ready(function() {
	/*security incident*/
	displaySecIncidents();
	
	/*display health and avai;*/
	displayHealthAvailIncidents();
	
	/*display requests*/
	displayRequests();
	
	/*display feeds*/
	displayNotifFeeds();
	
	/*display event processing funnel*/
	drawFunnel();
	
	/*display site to site vpn tunnel*/
	displayVPN();
	
	/*load grid onchange*/
	$('[name="incident_secincident_state"]').change(function() {
		loadIncident('incident_secincident');
	});
	
	$('[name="incident_healthavail_state"]').change(function() {
		loadIncident('incident_healthavail');
	});
	
	$('[name="requests_list_state"]').change(function() {
		loadIncident('requests_list');
	});
	
	/*bulletin board ticker*/
	if($('#bulletinFeed').length > 0)
	{
		$("notif_board").html($("#feedsdiv").html());
		$('[name=notif_filter]').change(function() {
			
			var notifview = $.trim($(this).val());
			if(notifview == 'grid')
			{
				$("notif_board").html($("#feedsdiv").html());
			}
			else
			{
				$("notif_board").html($("#bulletinFeed").vTicker());
			}
		});
	}
});
function displaySecIncidents()
{
	if($('#incident_secincident').length > 0)
	{
		var serviceMenuType = false;
		if($('[name=servicemenutype]').length > 0)
		{
			serviceMenuType = $.trim($('[name=servicemenutype]').val());
		}
		
	    var grid = $('#incident_secincident');
	    var getServicesUrl = strSecIncidentsUrl;
	    
	    grid.jqGrid({
	    	defaults : {
	    	        emptyrecords: 'No record to view'
	    	},
	    	datatype: 'json',
	    	url: getServicesUrl+"?servicemenuname="+serviceMenuType,
	    	colNames:[_('ID'), _('ID'), _('Title'), _('Opened'), _('Last Activity')],
	        colModel:[
	            {name:'id', width:65, sorttype: 'int', hidden:true,  jsonmap: 'cell.id'},
	            {name:'ticket_id', sorttype: 'int', sortable:true, align:'center', width:'10%', jsonmap: 'cell.ticket_id'},
	            {name:'title', sortable:true, width:'40%', jsonmap: 'cell.title'},
	            {name:'opened_date', align:'center', sortable:true, width:'25%', jsonmap: 'cell.opened_date'},
	            {name:'last_activity', width:'25%', sortable:true, align:'center', jsonmap: 'cell.last_activity'}
	        ],
	        autowidth: true,
	        shrinktofit: true,
	        rowNum:100000000,
	        gridview: true,
	        rowList:[10,50,100,100000000],
	        //pager: 'incident_secincidentPager',
	        //pagerpos: 'left',
	        sortname: 'cell.title',
	        viewrecords: true,
	        sortorder: 'desc',
	        loadonce: true,
	        caption:'',
	        altRows:true,
	        altclass:'jqg-altrow',
	        onSelectRow: function (id){
	        	//added by Senthil for POPUP
	        	$('#incident_secincident_details_cont').show();
	        	 $('#incident_secincident_details').removeClass('success-height');
	        	$('body').append("<div id='fade'></div>");
	        	
	        	$('#fade').css({'filter' : 'alpha(opacity=60)'}).fadeIn();
	        	var popupTopMargin = ($('#incident_secincident_details_cont').height()+10) / 2;
	        	var popupLeftMargin = ($('#incident_secincident_details_cont').width()+10) / 2;
	        	$('#incident_secincident_details_cont').css({
	        		"margin-top": -popupTopMargin, "margin-left": -popupLeftMargin
	        	});
	        	//end by Senthil S
	        	
	        	// Set top and left added by Oliver
	        	/*var topAbsolute = 150;
	        	var size_width = window.innerWidth || document.body.clientWidth;
	        	var leftAbsolute = (size_width / 2) - ($('#requests_list_details_cont').width() / 2);
	        	
	        	$('#requests_list_details_cont').css({
	        		'top' : topAbsolute, 
	        		//'left' : leftAbsolute, 
	        		'position' : 'absolute'
	        	});*/
	        	
	        	//$('html,body').scrollTop(0);
	        	
                var ticketid = id;
                var type = 'secincident';
                if(ticketid)
                {
                	$.ajax({
                	     type: 'GET',
                	     url: strIncidentViewUrl,
                	     data: {ticketid:ticketid, type:type},
                	     beforeSend: function()
                	     {
                	    	$('#incident_secincident_details').html('');
                	    	if($('#incident_secincident_details_loader').is(':visible')){
                     			return false;
                     		}
                     		loading_request(true, 'incident_secincident_details_loader');
                	     },
                	     success : function(html)
                	     {
                	    	 $('#incident_secincident_details').html(html);
                	    	
                	    	 /*add ticket response*/
                	    	 composeMsg(ticketid);
                	    	 /*end ticket response*/
                	    	 
                	    	 /* this is for close button added  by Senthil S*/
                	    	 $('#incident_secincident_details_cont').append('<div class="popup-close">'+_("Close this window")+'</div>');
                	    	 $('.popup-close').click(function(){
             	        		$('#fade').remove(); $('#incident_secincident_details_cont').hide();
             	        	}); 
                	    	 /* end*/
                	     },
                	     error: function()
                	     {
                	    	 $('#error_incident_secincident_details').show();
                	     },
                	     complete: function()
                	     {
                	    	 loading_request(false, 'incident_secincident_details_loader');
                	    	 $('#incident_secincident_details').addClass('success-height');
                	     }
                	 });
                }
	        },
	        gridComplete: function() {
	        	$('.ui-jqgrid-bdiv').css({overflow:'hidden'});
	        	$('#no_incident_secincident').html('');
	        	var recs = parseInt(grid.getGridParam("records"),10);
	            if (isNaN(recs) || recs == 0) {
	                $('#no_incident_secincident').html('<div align="center">'+_("No tickets to display")+'</div>'); 
	            }
	            else {
	                $('#secindidentdiv').show();
	            }
	        },
	        jsonReader : {
	      	     root: 'rows',
	      	     repeatitems: false,
	      	     id: 'id'
	      	   },
	        height: '100%'
	    });
	    
	    //disable cursor pointer for unsortable columns
	    var cm = grid[0].p.colModel;
	    $.each(grid[0].grid.headers, function(index, value) {
	        var cmi = cm[index], colName = cmi.name;
	        if(!cmi.sortable && colName !== 'rn' && colName !== 'cb' && colName !== 'subgrid') {
	            $('div.ui-jqgrid-sortable',value.el).css({cursor:'default'});
	        }
	    });
	    grid.jqGrid('navGrid','#incident_secincidentPager',{add:false,edit:false,del:false,search:false,refresh:false});
	    
	}
}

function displayHealthAvailIncidents()
{
	/*health and availability incidents*/
	if($('#incident_healthavail').length > 0)
	{
		var serviceMenuType = false;
		if($('[name=servicemenutype]').length > 0)
		{
			serviceMenuType = $.trim($('[name=servicemenutype]').val());
		}
			    
	    var grid = $('#incident_healthavail');
	    var getServicesUrl = strHealthAvailUrl;
	    grid.jqGrid({
	    	defaults : {
	    	        emptyrecords: _('No record to view')
	    	},
	    	datatype: 'json',
	    	url: getServicesUrl+"?servicemenuname="+serviceMenuType,
	    	colNames:[_('ID'), _('ID'), _('Title'), _('Opened'), _('Last Activity')],
	        colModel:[
	            {name:'id', width:65, sorttype: 'int', hidden:true},
	            {name:'ticket_id', sortable:true, sorttype: 'int', align:'center', width:'10%', jsonmap: 'cell.ticket_id'},
	            {name:'title', sortable:true, width:'40%', jsonmap: 'cell.title'},
	            {name:'opened_date', align:'center', sortable:true, width:'25%', jsonmap: 'cell.opened_date'},
	            {name:'last_activity', width:'25%', sortable:true, align:'center', jsonmap: 'cell.last_activity'}
	        ],
	        autowidth: true,
	        rowNum:100000000,
	        gridview: true,
	        //rowList:[10,50,100,100000000],
	        //pager: 'incident_healthavailPager',
	        //pagerpos: 'left',
	        sortname: 'cell.title',
	        viewrecords: true,
	        sortorder: "desc",
	        loadonce: true,
	        caption:"",
	        altRows:true,
	        altclass:'jqg-altrow',
	        onSelectRow: function (id){
	         	/*added by Senthil for POPUP*/
	        	$('#incident_healthavail_details_cont').show();
	        	$('#incident_healthavail_details').removeClass('success-height');
	        	$('body').append("<div id='fade'></div>");
	        	
	        	$('#fade').css({'filter' : 'alpha(opacity=60)'}).fadeIn();
	        	var popupTopMargin = ($('#incident_healthavail_details_cont').height()+10) / 2;
	        	var popupLeftMargin = ($('#incident_healthavail_details_cont').width()+10) / 2;
	        	$('#incident_healthavail_details_cont').css({
	        		"margin-top": -popupTopMargin, "margin-left": -popupLeftMargin
	        	});
	        	//end by Senthil S*/
	                var ticketid = id;
	                var type = 'healthavail';
	                if(ticketid)
	                {
	                	$.ajax({
	                	     type: 'GET',
	                	     url: strIncidentViewUrl,
	                	     data: {ticketid:ticketid, type:type},
	                	     beforeSend: function()
	                	     {
	                	    	$('#incident_healthavail_details').html('');
	                	    	if($('#incident_healthavail_details_loader').is(':visible')){
	                     			return false;
	                     		}
	                     		loading_request(true, 'incident_healthavail_details_loader');
	                	     },
	                	     success : function(html)
	                	     {
	                	    	 $('#incident_healthavail_details').html(html);
	                	    	 
	                	    	 /*add ticket response*/
	                	    	 composeMsg(ticketid);
	                	    	 /*end ticket response*/

	                	    	 
	                	    	 /* this is for close button added  by Senthil S*/
	                	    	 $('#incident_healthavail_details_cont').append('<div class="popup-close">'+_("Close this window")+'</div>');
	                	    	 $('.popup-close').click(function(){
	             	        		$('#fade').remove();$('#incident_healthavail_details_cont').hide();
	             	        	}); 
	                	    	 /* end */
	                	     },
	                	     error: function()
	                	     {
	                	    	 $('#error_incident_healthavail_details').show();
	                	     },
	                	     complete: function()
	                	     {
	                	    	 loading_request(false, 'incident_healthavail_details_loader');
	                	    	$('#incident_healthavail_details').addClass('success-height');
	                	     }
	                	 });
	                }
	        },
	        gridComplete: function() {
	        	$('.ui-jqgrid-bdiv').css({overflow:'hidden'});
	        	$('#no_incident_healthavail').html('');
	        	var recs = parseInt(grid.getGridParam("records"),10);
	            if (isNaN(recs) || recs == 0) {
	                $('#no_incident_healthavail').html('<div align="center">'+_("No tickets to display")+'</div>'); 
	            }
	            else {
	                $('#healthavaildiv').show();
	            }
	        },
	        jsonReader : {
	      	     root: 'rows',
	      	     repeatitems: false,
	      	     id: 'id'
	      	   },
	        height: '100%'
	    });
	    
	    //disable cursor pointer for unsortable columns
	    var cm = grid[0].p.colModel;
	    $.each(grid[0].grid.headers, function(index, value) {
	        var cmi = cm[index], colName = cmi.name;
	        if(!cmi.sortable && colName !== 'rn' && colName !== 'cb' && colName !== 'subgrid') {
	            $('div.ui-jqgrid-sortable',value.el).css({cursor:'default'});
	        }
	    });
	    grid.jqGrid('navGrid','#incident_healthavailPager',{add:false,edit:false,del:false,search:false,refresh:false});
	}
}

function displayRequests()
{
	/*requests*/
	if($('#requests_list').length > 0)
	{
		var serviceMenuType = false;
		if($('[name=servicemenutype]').length > 0)
		{
			serviceMenuType = $.trim($('[name=servicemenutype]').val());
		}
		
	    var grid = $('#requests_list');
	    var getServicesUrl = strRequestsUrl;
	    grid.jqGrid({
	    	defaults : {
	    	        emptyrecords: _('No record to view')
	    	},
	    	datatype: 'json',
	    	url: getServicesUrl+"?servicemenuname="+serviceMenuType,
	    	colNames:[_('ID'), _('ID'), _('Request Type'), _('Title'), _('Opened'), _('Last Activity')],
	        colModel:[
	            {name:'id', width:'10%', sorttype: 'int', hidden:true,  jsonmap: 'cell.id'},
	            {name:'ticket_id', sortable:true, sorttype: 'int', align:'center', width:'7%', jsonmap: 'cell.ticket_id'},
	            {name:'request_type', sortable:true, align:'left', width:'12%', jsonmap: 'cell.request_type'},
	            {name:'title', sortable:true, width:'20%', jsonmap: 'cell.title'},
	            {name:'opened_date', align:'center', sortable:true, width:'17%', jsonmap: 'cell.opened_date'},
	            {name:'last_activity', width:'17%', sortable:true, align:'center', jsonmap: 'cell.last_activity'}
	        ],
	        autowidth: true,
	        rowNum:100000000,
	        gridview: true,
	        rowList:[20,50,100,100000000],
	        //pager: '#requests_listPager',
	        //pagerpos: 'left',
	        sortname: 'cell.title',
	        viewrecords: true,
	        sortorder: 'desc',
	        loadonce: true,
	        caption:'',
	        altRows:true,
	        altclass:'jqg-altrow',
	        onSelectRow: function (id){
	        	/*added by Senthil for POPUP*/
	        	$('#requests_list_details_cont').show();
	        	$('#requests_list_details').removeClass('success-height');
	        	$('body').append("<div id='fade'></div>");
	        	
	        	$('#fade').css({'filter' : 'alpha(opacity=60)'}).fadeIn();
	        	 var popupTopMargin = ($('#requests_list_details_cont').height()+10) / 2;
	        	var popupLeftMargin = ($('#requests_list_details_cont').width()+10) / 2;
	        	$('#requests_list_details_cont').css({
	        		"margin-top": -popupTopMargin, "margin-left": -popupLeftMargin
	        	});
	        	
	        	//end by Senthil S*/
                
	        	// Set top and left added by Oliver
	        	/*var topAbsolute = 150;
	        	var size_width = window.innerWidth || document.body.clientWidth;
	        	var leftAbsolute = (size_width / 2) - ($('#requests_list_details_cont').width() / 2);
	        	
	        	$('#requests_list_details_cont').css({
	        		'top' : topAbsolute, 
	        		'left' : leftAbsolute, 
	        		'position' : 'absolute'
	        	});*/
	        	
	        	//$('html,body').scrollTop(0);
	        	
	        	var ticketid = id;
                var type = 'request';
                if(ticketid)
                {	
                	$.ajax({
                	     type: 'GET',
                	     url: strIncidentViewUrl,
                	     data: {ticketid:ticketid, type:type},
                	     beforeSend: function()
                	     {
                	    	 //alert(strIncidentViewUrl);
                	    	$('#requests_list_details').html('');
                	    	if($('#requests_list_details_loader').is(':visible')){
                     			return false;
                     		}
                     		loading_request(true, 'requests_list_details_loader');
                	     },
                	     success : function(html)
                	     {
                	    	 $('#requests_list_details').html(html);
                	    	 
                	    	 /*add ticket response*/
                	    	 composeMsg(ticketid);
                	    	 /*end ticket response*/
                	    	 
                	    	 /* this is for close button added  by Senthil S*/
                	    	 $('#requests_list_details_cont').append('<div class="popup-close">'+_("Close this window")+'</div>');
                	    	 $('.popup-close').click(function(){
             	        		$('#fade').remove();$('#requests_list_details_cont').hide();
             	        	}); 
                	    	 /* end */
                	     },
                	     error: function()
                	     {
                	    	 $('#error_requests_list_details').show();
                	     },
                	     complete: function()
                	     {
                	    	 loading_request(false, 'requests_list_details_loader');
                	    	$('#requests_list_details').addClass('success-height');
                	     }
                	    
                	 });
                }
	        },
	        gridComplete: function() {
	        	$('.ui-jqgrid-bdiv').css({overflow:'hidden'});
	        	$('#no_request').html('');
	        	var recs = parseInt(grid.getGridParam("records"),10);
	            if (isNaN(recs) || recs == 0) {
	                $('#no_request').html('<div align="center">'+_("No requests to display")+'</div>'); 
	            }
	            else {
	                $('#requestdiv').show();
	            }
	        },
	        jsonReader : {
	      	     root: 'rows',
	      	     repeatitems: false,
	      	     id: 'id'
	      	   },
	        height: '100%'
	    });
	    
	    //disable cursor pointer for unsortable columns
	    var cm = grid[0].p.colModel;
	    $.each(grid[0].grid.headers, function(index, value) {
	        var cmi = cm[index], colName = cmi.name;
	        if(!cmi.sortable && colName !== 'rn' && colName !== 'cb' && colName !== 'subgrid') {
	            $('div.ui-jqgrid-sortable',value.el).css({cursor:'default'});
	        }
	    });
	    grid.jqGrid('navGrid','#requests_listPager',{add:false,edit:false,del:false,search:true,refresh:false});
	}
		
}


function displayNotifFeeds()
{
	/*feeds*/
	
	if($('#feeds_list').length > 0)
	{
	    var grid = $('#feeds_list');
	    var getFeedsUrl = strFeedsUrl;
	    grid.jqGrid({
	    	defaults : {
	    	        emptyrecords: _('No record to view')
	    	},
	    	datatype: 'json',
	    	url: getFeedsUrl,
	    	colNames:['ID', _('Date Posted'), _('Title')],
	        colModel:[
	            {name:'id', width:65, sorttype: 'int', hidden:true,  jsonmap: 'cell.id'},
	            {name:'date_posted', index: 'date_posted', sortable:true, sorttype:'date', align:'left', width:'30%', jsonmap: 'cell.date_posted', formatter: 'date',
	            	formatoptions: {srcformat:"ISO8601Short", newformat:"l, F d, Y"} },	
	            {name:'title', sortable:true, width:'70%', jsonmap: 'cell.title'}
	        ],
	        autowidth: true,
	        rowNum:100000000,
	        gridview: true,
	        rowList:[20,50,100,100000000],
	        sortname: 'cell.date_posted',
	        viewrecords: true,
	        sortorder: 'desc',
	        loadonce: true,
	        caption:'',
	        altRows:true,
      	    altclass:'jqg-altrow',
	        onSelectRow: function (id){
	        	/*added by Senthil for POPUP*/
	        	$('#feeds_list_details_cont').show();
	        	$('#feeds_list_details').removeClass('success-height');
	        	$('body').append("<div id='fade'></div>");
	        	
	        	$('#fade').css({'filter' : 'alpha(opacity=60)'}).fadeIn();
	        	var popupTopMargin = ($('#feeds_list_details_cont').height()+10) / 2;
	        	var popupLeftMargin = ($('#feeds_list_details_cont').width()+10) / 2;
	        	$('#feeds_list_details_cont').css({
	        		"margin-top": -popupTopMargin, "margin-left": -popupLeftMargin
	        	});
	        	//end by Senthil S*/
                var ticketid = id;
                var type = 'feed';
                if(ticketid)
                {	
                	$.ajax({
               	     type: 'GET',
               	     url: strFeedsViewUrl,
               	     data: {ticketid:ticketid, type:type},
               	     beforeSend: function()
               	     {
               	    	$('#feeds_list_details').html('');
               	    	if($('#feeds_list_details_loader').is(':visible')){
                    			return false;
                    		}
                    		loading_request(true, 'feeds_list_details_loader');
               	     },
               	     success : function(html)
               	     {
               	    	 $('#feeds_list_details').html(html);
               	    	 
               	    	 /* this is for close button added  by Senthil S*/
               	    	 $('#feeds_list_details_cont').append('<div class="popup-close">Close this window</div>');
               	    	 $('.popup-close').click(function(){
            	        		$('#fade').remove();$('#feeds_list_details_cont').hide();
            	        	}); 
               	    	 /* end */
               	     },
               	     error: function()
               	     {
               	    	 $('#error_feeds_list_details').show();
               	     },
               	     complete: function()
               	     {
               	    	 loading_request(false, 'feeds_list_details_loader');
               	    	$('#feeds_list_details').addClass('success-height');
               	     }
               	 });
               }
	       },
	       gridComplete: function() {
	       	$('.ui-jqgrid-bdiv').css({overflow:'hidden'});
	       	$('#no_feeds_list').html('');
	       	var recs = parseInt(grid.getGridParam("records"),10);
	           if (isNaN(recs) || recs == 0) {
	               $('#no_feeds').html('<div align="center">'+_("No notication feeds at the moment")+'</div>'); 
	           }
	           else {
	               $('#feedsdiv').show();
	           }
	       },
	       jsonReader : {
	     	     root: 'rows',
	     	     repeatitems: false,
	     	     id: 'id'
	     	   },
	       height: '100%'
	    });
	    
	    //disable cursor pointer for unsortable columns
	    var cm = grid[0].p.colModel;
	    $.each(grid[0].grid.headers, function(index, value) {
	        var cmi = cm[index], colName = cmi.name;
	        if(!cmi.sortable && colName !== 'rn' && colName !== 'cb' && colName !== 'subgrid') {
	            $('div.ui-jqgrid-sortable',value.el).css({cursor:'default'});
	        }
	    });
	    grid.jqGrid('navGrid','#feeds_listPager',{add:false,edit:false,del:false,search:true,refresh:false});
	}
		
}

function loadIncident(page)
{
	var serviceMenuType = false;
	if($('[name=servicemenutype]').length > 0)
	{
		serviceMenuType = $.trim($('[name=servicemenutype]').val());
	}
	
	/*filter state - sec incident or health avail*/
	var incidentState = $('[name="'+page+'_state"]').val();
	var strUrl = strSecIncidentsUrl;

	/*determine which url to use*/
	if(page == 'incident_healthavail')
	{
		strUrl = strHealthAvailUrl;
	}
	else if(page == 'requests_list')
	{
		strUrl = strRequestsUrl;
	}
	
	$.ajax({
		type: 'GET',
		url: strUrl+'?servicemenuname='+serviceMenuType,
		data: {state:incidentState},
		beforeSend: function()
		{
			//$('#no_'+page).html('');
			if($('#'+page+'_details_loader').is(':visible')){
				return false;
			}
			loading_request(true, page+'_details_loader');
		},
		success : function(data)
		{
			$('#'+page).setGridParam({
				 datatype:'json', 
				 page:1, 
				 url : strUrl+'?state='+incidentState+'&servicemenuname='+serviceMenuType
			 }).trigger('reloadGrid');
			
			/*if(data.length < 12)
			{
				$('#no_'+page).html('<div align="center">No '+incidentState.toUpperCase()+' tickets to display</div>'); 
			}*/
		},
		error: function()
		{
			$('#error_'+page+'_details').show();
		},
		complete: function()
		{
			loading_request(false, page+'_details_loader');
		}
	});
}

function drawFunnel1()
{
	
	var strFunnelUrl = 'ajax/drawEvents.php';
	if($('#event_proc').length > 0)
	{
		var now = new Date();
		var currentdate = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),  now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
		var past6Hours = currentdate.setTime(currentdate.getTime() - 360*60*1000);
		var adjustedDate = new Date(past6Hours);
		var m = adjustedDate.getMonth()+1;
        var d = adjustedDate.getDate();
        var h = adjustedDate.getHours();
		var min = adjustedDate.getMinutes();
		var s = adjustedDate.getSeconds();
		
		if (m < 10) {
            m = '0' + m
        }
        
        if (d < 10) {
            d = '0' + d
        }
		
		if (h < 10) {
            h = '0' + h
        }
        
        if (min < 10) {
            min = '0' + min
        }
        
        if (s < 10) {
            s = '0' + s
        }
		
		var currDate = m +'-'+ d +'-'+adjustedDate.getFullYear();
		var currTime = h + ':' + min + ':' + s;
		
		$.getJSON(strFunnelUrl, function(json) {
		       
            chart = new Highcharts.Chart({
                chart: {
                	renderTo: 'event_proc',
    	            type: 'funnel',
    	            marginRight: 100,
    	            marginLeft: 75,
    	            spacingBottom: 20
                },
                colors: [
		                 '#238aa5', 
		                 '#e1663d',
		                 '#db3d74', 
		                 '#535e60', 
		                 '#6381b0' 
		              ],
	              title: {
	                  text: '<font size="1">* as of '+currDate+' '+currTime+' (GMT)</font>',
	                  floating: true,
	                  align: 'left',
	                  x: -10,
	                  verticalAlign: 'bottom',
	                  y: -10,
	                  useHTML: true
	              },
                
                credits: {
  				  enabled: false
                },
                plotOptions: {
    	            series: {
    	                dataLabels: {
    	                    enabled: true,
    	                    format: '<b>{point.name}</b><br />{point.y:,.0f}<br />',
    	                    color: 'black',
    	                    softConnector: true
    	                },
    	                neckWidth: '30%',
    	                neckHeight: '25%'
    	                
    	                //-- Other available options
    	                // height: pixels or percent
    	                // width: pixels or percent
    	            }
    	        },
    	        exporting: {
    	        	enabled: false
    	        },
    	        legend: {
    	            enabled: false
    	        },
    	        series: [{
    	        	name: 'count',
    	        	data: json
                }]
            });
        });
	}
}

function drawFunnel()
{
	$('#asof').hide();
	var strFunnelUrl = 'ajax/drawEvents.php';
	if($('#event_proc').length > 0)
	{

	    $.ajax({
   	     url: strFunnelUrl,
   	     data: 'json',
   	     beforeSend: function()
   	     {
   	    	if($('.event-flow').is(':visible')){
        			return false;
        		}
        		loading_request(true, 'event_loader');
   	     },
   	     success : function(json)
   	     {
   	    	if(json !== false)
   	    	{
   	    		var demo2 = '<div class="eventdiv" id="eventdiv" style="display:inline-block"></div>';
   				$("#event_proc").empty();
   		        $('#event_proc').html(demo2);
   		        
   		        chart1=new cfx.Chart();
   		        var funnel = new cfx.Funnel.Funnel();
   				chart1.setGalleryAttributes(funnel);
   				
   				funnel.setTipHeight(25);
   				funnel.setTipWidth(10);
   				
   				
   				var data = chart1.getData();
   				data.setSeries(1);
   				data.setPoints(4);
   				
   				chart1.getAnimations().getLoad().setEnabled(true);
   				
   				/*labels*/
   				chart1.getAllSeries().getPointLabels().setVisible(true);
   				chart1.getAllSeries().getPointLabels().setRichText(true);
   				chart1.getAllSeries().getPointLabels().setAlignment(cfx.StringAlignment.Far);
   				chart1.getAllSeries().getPointLabels().setFormat("%l");
   				
   				chart1.getLegendBox().setVisible(false);
   				chart1.getToolTips().setEnabled(false);
   				chart1.setBackColor("#FFFFFF");
   				chart1.setPlotAreaColor("#FFFFFF");
   				chart1.getView3D().setEnabled(false);
   				
   	   	    	/* construct the data */
   				// get total
   				var myTotal = 0;
   				$.each(json, function( key, value ) {
   	 				arrVal = value.toString();
   	 				funnelName = arrVal.split(',');
   	 				myTotal += parseInt(funnelName[1]);
   	 			});
   				
   				// plot graph in percentage
   	 			var funnelName;
   	 			var arrVal;
   	 			
   				var intCount = 0;
   				var newValue = 0;
   	 			$.each(json, function( key, value ) {
   	 				arrVal = value.toString();
   	 				funnelName = arrVal.split(',');
   	 				intCount = parseInt(funnelName[1]);
   	 				newValue = (intCount / myTotal) * 100;

   	 				if (newValue < 5) {
   	 					newValue = 5;
   	 					if (key == 0) {
   	 						newValue = 3;
   	 					}
   	 				}
   	 				
   	 				data.setItem(0, key, newValue);
   	 				data.getLabels().setItem(key, funnelName[0]+"\n"+'('+funnelName[1]+')');
   	 			});
   	 			/*end construction of data*/
   	 			
   	 			var divHolder = document.getElementById('event_proc');
   	            chart1.create(divHolder);
   	            $('#asof').show();
   	    	}
   	    	else
   	    	{
   	    		$('#event_proc').css("height","5px");
   	    		var noLog = _("No funnel to display as the event logs are not available");
   	    		$('#nofunnel').html(noLog);
   	    		//$('.event-flow').hide();
   	    	}	
   	     },
   	     error: function()
   	     {
   	    	 $('#error_event').show();
   	     },
   	     complete: function()
   	     {
   	    	 loading_request(false, 'event_loader');
   	    	//$('.event-flow').show();
   	     }
   	 });
		
	}
}

function displayVPN()
{
	var strVPNUrl =  'ajax/displayvpn.php';
	if($('#vpn_tunnel').length > 0)
	{
	    var grid = $('#vpn_tunnel');
	    var getServicesUrl = strVPNUrl;
	    grid.jqGrid({
	    	defaults : {
	    	        emptyrecords: 'No record to view'
	    	},
	    	datatype: 'json',
	    	url: getServicesUrl,
	    	colNames:[_('ID'), _('Device'), _('Tunnel'), _('Status'), _('Chart')],
	        colModel:[
	            {name:'id', width:65, sorttype: 'int', hidden:true,  jsonmap: 'cell.id'},
	            {name:'device_name', sortable:true, align:'left', width:'50%', jsonmap: 'cell.device_name'},
	            {name:'tunnel', sortable:true, width:'30%', jsonmap: 'cell.tunnel'},
	            {name:'status', align:'center', sortable:true, width:'10%', jsonmap: 'cell.status'},
	            {name:'chart', width:'10%', sortable:true, align:'center', jsonmap: 'cell.chart'}
	        ],
	        autowidth: true,
	        shrinktofit: true,
	        rowNum:100000000,
	        gridview: true,
	        rowList:[10,50,100,100000000],
	        sortname: 'cell.device_name',
	        viewrecords: true,
	        sortorder: 'desc',
	        loadonce: true,
	        caption:'',
	        altRows:true,
	        altclass:'jqg-altrow',
	        onSelectRow: function (id){
	        	$('#op5graph_container_div').show();
	        	
	        	$('body').append("<div id='fade'></div>");
	        	$('#fade').css({'filter' : 'alpha(opacity=60)'}).fadeIn();
	        	
	        	
	        	var popupTopMargin = ($('#op5graph_container_div').height()+10) / 2;
	        	var popupLeftMargin = ($('#op5graph_container_div').width()+10) / 2;
	        	$('#op5graph_container_div').css({
	        		"margin-top": -popupTopMargin, "margin-left": -popupLeftMargin
	        	});
	        	
	        	
	        	 
	    	    	$('[name=op5graph_container]').html('');
	    	    	if($('#chart_loader').is(':visible')){
	         			return false;
	         		}
	    	    	
	         		loading_request(true, 'chart_loader');
	        	
	         		$('[name=op5graph_container]').html('<object type="text/html" class="object-wrap" data="'+id+'" style="overflow:hidden"></object>');
	         		/* this is for close button added  by Senthil S*/
	         		$('#op5graph_container_div').append('<div class="popup-close">'+_("Close this window")+'</div>');
	         		$('#op5graph_container_div').append('<div class="vpn-interactive-chart-heading">Interactive chart</div>');
	         		$('#op5graph_container_div').append('<div class="vpn-interactive-btns"><div id="f_hours">4H</div><div id="tw_hours">25H</div><div id="w_one">1W</div><div id="m_one">1M</div><div id="y_one">1Y</div></div>');
	         		
	         		$('.vpn-interactive-btns div#tw_hours').addClass('active-btn');
	         		vpnInteractiveChart(id);
	         		$('.popup-close').click(function(){
	         			$('#fade').remove();$('#op5graph_container_div').hide();
	         		}); 
	         		
	         		loading_request(false, 'chart_loader');
	         		
	         		/* end */
	        },
	        loadComplete: function() {
	        	$('.ui-jqgrid-bdiv').css({overflow:'hidden'});
	        	$('#no_vpn').html('');
	        	//loadOP5Graph();
	        	var recs = parseInt(grid.getGridParam("records"),10);
	            if (isNaN(recs) || recs == 0) {
	                $('#no_vpn').html('<div align="center">'+_("No VPN tunnel to monitor")+'</div>'); 
	            }
	            else {
	                $('#vpn_tunnel').show();
	            }
	        },
	        jsonReader : {
	      	     root: 'rows',
	      	     repeatitems: false,
	      	     id: 'id'
	      	   },
	        height: '100%'
	    });
	    
	    //disable cursor pointer for unsortable columns
	    var cm = grid[0].p.colModel;
	    $.each(grid[0].grid.headers, function(index, value) {
	        var cmi = cm[index], colName = cmi.name;
	        if(!cmi.sortable && colName !== 'rn' && colName !== 'cb' && colName !== 'subgrid') {
	            $('div.ui-jqgrid-sortable',value.el).css({cursor:'default'});
	        }
	    });
	    grid.jqGrid('navGrid','#vpn_tunnelPager',{add:false,edit:false,del:false,search:false,refresh:false});
		    
	}
}
function vpnInteractiveChart(op5Url){
	$('.vpn-interactive-btns div').click(function(){
		$('.vpn-interactive-btns div#tw_hours').removeClass('active-btn');
		$('.vpn-interactive-btns div').removeClass('active-btn');
		$(this).addClass('active-btn');
		var chartId = $.trim($(this).attr('id'));
		var OP5URLView = '';
		var op5View = '';
		if(chartId == 'f_hours')
		{
			op5View = '&view=0';
			
		}
		else if(chartId == 'tw_hours')
		{
			op5View = '&view=1';
			
		}
		else if(chartId == 'w_one')
		{
			op5View = '&view=2';
			
		}
		else if(chartId == 'm_one')
		{
			op5View = '&view=3';
			
		}
		else if(chartId == 'y_one')
		{
			op5View = '&view=4';
			
		}
		
		OP5URLView = op5Url+op5View;
		$('[name=op5graph_container]').html('<object type="text/html" class="object-wrap" data="'+OP5URLView+'" style="overflow:hidden"></object>');
	})
}

